<template>
  <div style="height: 100%;width: 100%;position: relative">
<!--    <button class="btn">返回上级</button>-->
    <div style="height: 100%;width: 100%" ref="echart">
      echart
    </div>
  </div>
</template>

<script>
import echarts from 'echarts'

export default {
  name: 'Echart',
  props: {
    chartData: {
      type: Object,
      default () {
        return {
          xData: [],
          series: []
        }
      }
    },
    isAxisChart: {
      type: Boolean,
      default: true
    },
    // 折线图
    type: {
      type: String,
      default: ''
    },
    isShowLegend: {
      type: Boolean,
      default: false
    },
    // 是否显示y轴线
    isAxisLine: {
      type: Boolean,
      default: false
    },
    // 是否显示y轴线的标点
    isAxisLabel: {
      type: Boolean,
      default: false
    },
    isShowYName: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    options () {
      return this.isAxisChart ? this.axisOption : this.normalOption
    }
  },
  data () {
    return {
      echart: null,
      axisOption: {
        legend: {
          show: this.isShowLegend,
          // data: ['2018', '2019', '2028'],
          x: 'center',
          y: 15,
          textStyle: {
            color: 'rgba(255,255,255,1)'
          }
        },
        color: ['#3398DB'],
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: [], // x轴的坐标数据
            axisTick: {
              alignWithLabel: true
            },
            // 网格样式
            splitLine: {
              show: false
              // lineStyle: {
              //   color: [],
              //   width: 1,
              //   type: 'solid'
              // }
            },
            // x轴的颜色和宽度
            axisLine: {
              lineStyle: {
                color: '#6076AD'
              }
            },
            nameTextStyle: {
              color: 'red'
            },
            // axisLabel: {
            //   color: '#57F8D6'
            // },
            axisLabel: {
              color: '#57F8D6',
              interval: 0 // 可以设置成 0 强制显示所有标签。
              // interval: 0,
              // rotate: 270,
              // formatter: function (value) {
              //   return value.split('').join('\n')
              // }
            },
            splitArea: {
              // show:true
            }
          }
        ],
        yAxis: [
          {
            // type : 'value',
            name: '',
            nameTextStyle: {
              color: '#57F8D6',
              fontSize: 16,
              padding: 10
            },
            axisLine: {
              show: this.isAxisLine, // y轴线消失
              lineStyle: {
                color: '#6076AD'
              }
            },
            // 网格样式
            splitLine: {
              show: true,
              lineStyle: {
                color: ['#6076AD'],
                width: 1,
                type: 'solid'
              }
            },
            axisLabel: {
              show: this.isAxisLabel, // 这行代码控制着坐标轴x轴的文字是否显示
              color: '#57F8D6'
            },
            lineStyle: {
              color: '#EDEDED' // 修改网格线颜色
            },
            axisTick: {
              show: false // y轴坐标点消失
            },
          }
        ],
        series: [
          {
            name: '',
            type: 'bar',
            barWidth: '35%',
            data: [], // y轴的坐标数据
            itemStyle: {
              normal: {
                  barBorderRadius: 3,
                  // 定制显示（按顺序）
                // barBorderRadius: 8,
                // 每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
                color: function (params) {
                  var colorList = [
                    ['#3D7ACA', '#00F5FF'],
                    ['#3B7AC9', '#DA3B80'],
                    ['#4EE6D0', '#00F5FF'],
                    ['#1271B2', '#00F5FF'],
                    ['#4776C4', '#D53F84'],
                    ['#0E57DA', '#3281D3'],
                    ['#57F8D6', '#3281D3']
                  ]
                  var index = params.dataIndex
                  if (params.dataIndex >= colorList.length) {
                    index = params.dataIndex % colorList.length
                  }
                  return new echarts.graphic.LinearGradient(0, 0, 0, 1,
                    [
                      {
                        offset: 0,
                        color: colorList[index][0]
                      },
                      {
                        offset: 1,
                        color: colorList[index][1]
                      }
                    ])
                },
                label: {
                  show: true, // 开启显示
                  position: 'top', // 在上方显示
                  textStyle: { // 数值样式
                    color: '#57F8D6',
                    fontSize: 13
                  }
                }
              }
            }
          }
        ]
      },
      normalOption: {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          x: 'right',
          y: 'bottom',
          textStyle: {
            color: []
          },
          data: [] // 显示头部的数据
        },
        series: [
          {
            name: '物种分析',
            legendHoverLink: true,
            hoverAnimation: true,
            // roseType: true,
            type: 'pie',
            radius: ['40%', '60%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: false,
            label: {
              // normal: {
              //     position: 'center'
              // },
              show: true,
              formatter: '{d}%',
              textStyle: {
                // color: 'black',
                fontWeight: 'normal',
                fontSize: 18
              }
            },
            itemStyle: {
              normal: {
                // 定制显示（按顺序）
                // barBorderRadius: 8,
                // 每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
                color: function (params) {
                  // build a color map as your need.
                  var colorList = [
                    '#FDB628', '#00F5FF', '#46D8CB', '#d48265'
                  ]
                  return colorList[params.dataIndex]
                }
              }
            },
            data: [] // 园的数据
          }
        ]
      }
    }
  },
  mounted () {
    this.initChart()
    window.addEventListener('resize', this.resizeChart)
  },
  destroyed () {
    window.removeEventListener('resize', this.resizeChart)
  },
  methods: {
    initChart () {
      this.initChartData()
      if (this.echart) {
        this.echart.setOption(this.options)
        this.echart.on('click', (param) => {

        })
      } else {
        this.echart = echarts.init(this.$refs.echart)
        this.echart.setOption(this.options)
        this.echart.on('click', (param) => {
          this.$emit('clickItem', param.name)
        })
      }
    },
    initChartData () {
      if (this.isAxisChart) {
        // console.log(this.multiarr(this.chartData.series))
        if (this.multiarr(this.chartData.series) === 2) {
          this.axisOption.xAxis[0].data = this.chartData.xData
          this.axisOption.yAxis[0].name = this.chartData.yName
          let arr = []
          let colorArr = [
            {},
            {
              color: '#d06d6a' // 改变折线颜色
            }
          ]
          this.chartData.series.forEach((item,index) => {
            let obj = {
              name: '',
              data: [],
              type: 'line',
              smooth: true, // 折线变曲线
              areaStyle: {} // 折线有面积
            }
            for (let i = 0; i < colorArr.length; i++) {
              obj.areaStyle = colorArr[index]
            }
            obj.data = item
            arr.push(obj)
          })
          for (let i = 0; i < this.chartData.name[0].length; i++) {
            arr[i].name = this.chartData.name[0][i]
          }
          arr.forEach(item => {
            this.axisOption.series.push(item)
          })
          console.log(this.axisOption.series)
        }
        if (this.multiarr(this.chartData.series) === 1) {
          this.axisOption.xAxis[0].data = this.chartData.xData
          this.axisOption.series[0].data = this.chartData.series
          this.axisOption.series[0].name = this.chartData.name ? this.chartData.name : '物种数量'
          this.axisOption.series[0].type = this.type ? this.type : 'bar'
          this.axisOption.series[0].smooth = true
        }
      } else {
        this.normalOption.legend.data = this.chartData.legendData
        this.normalOption.series[0].data = this.chartData.seriesData
      }
    },
    resizeChart () {
      this.echart ? this.echart.resize() : ''
    },
    multiarr (arr) {
      let a = 1
      for ( let i = 0; i < arr.length; i++) {
        if (arr[i] instanceof Array) {
          a++
          arr = arr[i]
          this.multiarr(arr)
        }
      }
      return a
    }

  },
  watch: {
    chartData: {
      handler: function () {
        this.initChart()
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>

</style>
